package com.zhenhao.xsq.utils;


import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.zhenhao.xsq.application.AppConfig;
import com.zhenhao.xsq.data.api.HttpAPIWrapper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author xlei
 * @Date 2018/7/11.
 */

public class UploadUtil {
    private static int curUploadImgokhttp = 0;
    private static List<String> urlList = new ArrayList<>();

    public static void uploadPicsOkhttp(Map map, final HttpAPIWrapper httpAPIWrapper, final List<String>
            list, final UploadFileCallBack callBack) {
        // TODO: 2024/9/20 暂时注释
        /*RequestBody fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                new File(list.get(curUploadImgokhttp)));
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", new File(list.get
                (curUploadImgokhttp)).getName(), fileRequestBody);
        Disposable subscribe = httpAPIWrapper.uploadFile(map, body).subscribe(new Consumer<FileEntity>() {
            @Override
            public void accept(@NonNull FileEntity commonBean) throws Exception {
                Logger.i("tag curUploadImgokhttp" + curUploadImgokhttp + "");
                curUploadImgokhttp++;
                urlList.add(commonBean.getData().getObjname());
//                    Logger.i("tag commonBean.getData()" + commonBean.getData() + "");
                if (curUploadImgokhttp == list.size()) {
                    curUploadImgokhttp = 0;
                    callBack.sucess(urlList);
                    urlList.clear();
                } else {
                    uploadPicsOkhttp(map, httpAPIWrapper, list, callBack);
                }

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                callBack.fail(throwable.toString());
                Logger.e("文件上传报错：" + throwable.toString());
                curUploadImgokhttp = 0;
                urlList.clear();
            }
        });*/
    }

    public static void uploadPicsOkhttpXunjian(Map map, final HttpAPIWrapper httpAPIWrapper, final List<String>
            list, final UploadFileCallBack callBack) {
        // TODO: 2024/9/20 暂时注释
        /*RequestBody fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                new File(list.get(curUploadImgokhttp)));
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", new File(list.get
                (curUploadImgokhttp)).getName(), fileRequestBody);
        Disposable subscribe = httpAPIWrapper.uploadXunjian(map, body).subscribe(new Consumer<PatrolFileEntity>() {
            @Override
            public void accept(@NonNull PatrolFileEntity commonBean) throws Exception {
                Logger.i("tag curUploadImgokhttp" + curUploadImgokhttp + "");
                curUploadImgokhttp++;
                urlList.add(commonBean.getData().get(0));
//                    Logger.i("tag commonBean.getData()" + commonBean.getData() + "");
                if (curUploadImgokhttp == list.size()) {
                    curUploadImgokhttp = 0;
                    callBack.sucess(urlList);
                    urlList.clear();
                } else {
                    uploadPicsOkhttpXunjian(map, httpAPIWrapper, list, callBack);
                }

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                callBack.fail(throwable.toString());
                Logger.e("文件上传报错：" + throwable.toString());
                curUploadImgokhttp = 0;
                urlList.clear();
            }
        });*/
    }

    //    public static void uploadPicsOkhttp(final HttpAPIWrapper httpAPIWrapper, final List<String>
//            list, final UploadFileCallBack callBack) {
//        RequestBody fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
//                Bitmap2Bytes(compressPixel(list.get(curUploadImgokhttp))));
////        Logger.e("--" + new File(list.get(curUploadImgokhttp)).length() + "--" + Bitmap2Bytes
////                (compressPixel(list.get(curUploadImgokhttp))).length);
//        MultipartBody.Part body = MultipartBody.Part.createFormData("file", new File(list.get
//                (curUploadImgokhttp)).getName(), fileRequestBody);
//        Disposable subscribe = httpAPIWrapper.uploadFile(body).subscribe(new Consumer<FileEntity>
//                () {
//            @Override
//            public void accept(@NonNull FileEntity commonBean) throws Exception {
//                Logger.i("tag curUploadImgokhttp" + curUploadImgokhttp + "");
//                curUploadImgokhttp++;
//                urlList.add(commonBean.getList().getUrl());
////                    Logger.i("tag commonBean.getData()" + commonBean.getData() + "");
//                if (curUploadImgokhttp == list.size()) {
//                    curUploadImgokhttp = 0;
//                    callBack.sucess(urlList);
//                    urlList.clear();
//                } else {
//                    uploadPicsOkhttp(httpAPIWrapper, list, callBack);
//                }
//
//            }
//        }, new Consumer<Throwable>() {
//            @Override
//            public void accept(@NonNull Throwable throwable) throws Exception {
//                callBack.fail(throwable.toString());
//                Logger.e("文件上传报错：" + throwable.toString());
//                curUploadImgokhttp = 0;
//                urlList.clear();
//            }
//        });
//    }
    public interface UploadFileCallBack {
        void sucess(List<String> url);

        void fail(String msg);
    }

    private static Bitmap compressPixel(String filePath) {
        Bitmap bmp = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //setting inSampleSize value allows to load a scaled down version of the original image
        options.inSampleSize = 2;

        //inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[16 * 1024];
        try {
            //load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
            if (bmp == null) {

                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(filePath);
                    BitmapFactory.decodeStream(inputStream, null, options);
                    inputStream.close();
                } catch (FileNotFoundException exception) {
                    exception.printStackTrace();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        } finally {
            return bmp;
        }
    }

    /**
     * 把Bitmap转Byte
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    //    检查版本更新，跳转到腾讯应用宝进行下载
    public static void intit_getClick(Context mContext) {
        if (isAvilible(mContext, "com.tencent.android.qqdownloader")) {// 市场存在
//			Log.e("wh", "跳转下载");
            launchAppDetail(AppConfig.getInstance(), "com.zhenhao.xsq", "com.tencent.android.qqdownloader");
        } else {
            Uri uri = Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.zhenhao.xsq");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            mContext.startActivity(it);
        }
    }

    // 判断市场是否存在的方法
    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
// 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }

    /**
     * 启动到app详情界面
     *
     * @param appPkg    App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) {
                return;
            }
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
